package n_swing_jtable;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class TableEventListener2 implements ActionListener {
	JTable table;
	JButton appendBtn, deleteBtn, printBtn;
	JTableEx2 jt2;
	
	public TableEventListener2(JTable table){
		this.table = table;
	}
	
	public TableEventListener2(JTableEx2 t){
		this.jt2 = t;
		this.table = jt2.table;
	}
	
	public TableEventListener2(JTable table, JButton appendBtn, JButton deleteBtn, JButton printBtn){
		this.table = table;
		this.appendBtn = appendBtn;
		this.deleteBtn = deleteBtn;
		this.printBtn = printBtn;
		
	}

	public void actionPerformed(ActionEvent ev) {
	
		if(((JButton)ev.getSource()).getText().equals("Append")){
			String data[] = {
					jt2.irum.getText(),
					jt2.address.getText(),
					jt2.phone.getText()
			};
			DefaultTableModel model = (DefaultTableModel)table.getModel();
			model.addRow(data);
		}
		
		if(((JButton)ev.getSource()).getText().equals("Delete")){
			int row = table.getSelectedRow();
			if( row == -1) return;
			DefaultTableModel model = (DefaultTableModel)table.getModel();
			model.removeRow(row);
		}
		
		if(((JButton)ev.getSource()).getText().equals("Print")){
			int row, column;
			TableModel model = (TableModel)table.getModel();
			row = table.getRowCount();
			column = table.getColumnCount();
			
			for(int i=0 ; i<column ; i++){
				System.out.print(model.getColumnName(i) + "\t\t");
			}
			System.out.println();
			for(int i=0 ; i<row ; i++){
				for(int j=0 ; j<column ; j++){
					System.out.print(model.getValueAt(i,j) + "\t\t");
				}
				System.out.println();
			}
			
			
		}
	}

}
